from .view import AuthorizationView, User, Role, UserView, RoleUserView
from . import schema
from typing import List
from fastapi import APIRouter, Depends, Security
from package.connector.sql_db import db
from package.fastapi import permission


router_owner = APIRouter(prefix='/owner', tags=['个人信息'])
router_user = APIRouter(prefix='/rbac', tags=['用户角色权限'])

router_meta = {'module': '系统管理', 'sub_module': '用户管理'}


# -------------------------------------------个人信息----------------------------------------------------------------
@router_owner.get('/', response_model=schema.OwenerOut, openapi_extra=router_meta, name='owner_get', summary='个人信息获取')
def owner_get(session=Depends(db.get_session),
              user=Security(permission.security, scopes=[])):
    return User.get_item(session, filter_=[User.id == user['id']])


@router_owner.patch('/', openapi_extra=router_meta, name='owner_patch', summary='个人信息修改')
def owner_patch(session=Depends(db.get_session),
                body: schema.EditOwner = None,
                user=Security(permission.security, scopes=[])):
    return User.update_item(session, filter_=[User.id == user['id']], update=body.dict(exclude_unset=True))


@router_owner.patch('/password', openapi_extra=router_meta, name='owner_password', summary='个人密码修改')
def owner_password(session=Depends(db.get_session),
                   body: schema.EditPassword = None,
                   user=Security(permission.security, scopes=[])):
    return UserView.edit_password(session, id=user['id'], old=body.old, new=body.password)


@router_owner.post('/authorization', response_model=schema.AuthorizationOut, openapi_extra=router_meta,
                   name='authorization_post', summary='创建授权码')
def authorization_post(session=Depends(db.get_session),
                       body: schema.Authorization = None,
                       user=Security(permission.security, scopes=[])):
    return AuthorizationView.post_authorization(session, user_id=user['id'], **body.dict())


@router_owner.patch('/authorization/{id}', response_model=schema.AuthorizationOut, openapi_extra=router_meta,
                    name='authorization_patch', summary='授权码修改')
def authorization_patch(id: str,
                        session=Depends(db.get_session),
                        body: schema.Authorization = None,
                        user=Security(permission.security, scopes=[])):
    return AuthorizationView.update_item(session, filter_=[AuthorizationView.id == id], update=body.dict(exclude_unset=True))


@router_owner.delete('/authorization', openapi_extra=router_meta, name='authorization_delete', summary='删除个人授权')
def authorization_delete(session=Depends(db.get_session),
                         body: schema.BatchId = None,
                         user=Security(permission.security, scopes=[])):
    return AuthorizationView.delete_authorization(session, ids=body.ids)


# -------------------------------------------用户管理----------------------------------------------------------------
@router_user.get('/user', response_model=schema.PageUsers, openapi_extra=router_meta, name='user_list_get',
                 summary='用户列表')
def user_get(q: str = None,
             page: int = 1,
             page_size: int = 10,
             order_by: str = 'created_at desc',
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['user:read'])):
    return User.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_user.post('/user', response_model=schema.UserOut, openapi_extra=router_meta, name='user_post', summary='用户创建')
def user_post(body: schema.CreateUser,
              session=Depends(db.get_session),
              user=Security(permission.security, scopes=['user:write'])):
    return User.create_item(session, body=body.dict())


@router_user.get('/user/{id}', response_model=schema.UserOut, openapi_extra=router_meta, name='user_get',
                 summary='用户详情')
def user_get(id: str,
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['user:read'])):
    return User.get_item(session, filter_=[User.id == id])


@router_user.patch('/user/{id}', response_model=schema.UserOut, openapi_extra=router_meta, name='user_patch',
                   summary='用户修改')
def user_patch(id: str,
               body: schema.EditUser,
               session=Depends(db.get_session),
               user=Security(permission.security, scopes=['user:write'])):
    return User.update_item(session, filter_=[User.id == id], update=body.dict(exclude_unset=True))


@router_user.delete('/user', openapi_extra=router_meta, name='user_delete', summary='用户删除')
def user_delete(body: schema.BatchId,
                session=Depends(db.get_session),
                user=Security(permission.security, scopes=['user:write'])):
    return {'count': User.delete_items(session, filter_=[User.id.in_(body.ids), User.inner != True])}


@router_user.patch('/user/{id}/enable', response_model=schema.UserOut, openapi_extra=router_meta, name='user_enable',
                   summary='账号启用/禁用')
def user_enable(id: str,
                body: schema.EnableUser,
                session=Depends(db.get_session),
                user=Security(permission.security, scopes=['user:write'])):
    return User.update_item(session, filter_=[User.id == id], update=body.dict(exclude_unset=True))


# -------------------------------------------角色管理----------------------------------------------------------------
@router_user.get('/role', response_model=schema.PageRoles,
                 openapi_extra=router_meta, name='role_list_get', summary='角色列表')
def role_items(q: str = None,
               page: int = 1,
               page_size: int = 10,
               order_by: str = 'created_at desc',
               session=Depends(db.get_session),
               user=Security(permission.security, scopes=['role:read'])):
    return Role.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_user.get('/role/{id}', response_model=schema.RoleOut, openapi_extra=router_meta, name='role_get',
                 summary='角色详情')
def role_item(id: str,
              session=Depends(db.get_session),
              user=Security(permission.security, scopes=['role:read'])):
    return Role.get_item(session, filter_=[Role.id == id])


@router_user.post('/role', response_model=schema.RoleOut, openapi_extra=router_meta, name='role_post', summary='角色创建')
def role_post(body: schema.CreateRole,
              session=Depends(db.get_session),
              user=Security(permission.security, scopes=['role:write'])):
    return Role.create_item(session, body.dict())


@router_user.patch('/role/{id}', response_model=schema.RoleOut, openapi_extra=router_meta, name='role_patch',
                   summary='角色修改')
def role_patch(id: str,
               body: schema.EditRole,
               session=Depends(db.get_session),
               user=Security(permission.security, scopes=['role:write'])):
    return Role.update_item(session, filter_=[Role.id == id], update=body.dict(exclude_unset=True))


@router_user.delete('/role', openapi_extra=router_meta, name='role_post', summary='角色删除')
def role_delete(body: schema.BatchId,
                session=Depends(db.get_session),
                user=Security(permission.security, scopes=['role:write'])):
    count = Role.delete_items(session, filter_=[Role.id.in_(body.ids), Role.inner != True])
    return {'count': count}


# -------------------------------------------角色用户管理----------------------------------------------------------------
@router_user.get('/role/{id}/user', response_model=List[schema.UserOut], openapi_extra=router_meta,
                 name='role_user_get',
                 summary='角色下获取关联用户')
def get_role_users(id: str,
                   q: str = None,
                   session=Depends(db.get_session),
                   user=Security(permission.security, scopes=['role:read'])):
    return RoleUserView.get_role_users(session, id, q)


@router_user.post('/role/{id}/user', openapi_extra=router_meta, name='role_user_bind',
                  summary='角色下增加关联用户')
def bind_role_users(id: str,
                    body: schema.BatchId,
                    session=Depends(db.get_session),
                    user=Security(permission.security, scopes=['role:write'])):
    return RoleUserView.bind_role_users(session, id, body.ids)


@router_user.delete('/role/{id}/user', openapi_extra=router_meta, name='role_user_delete',
                    summary='角色下解除关联用户')
def delete_role_users(id: str,
                      body: schema.BatchId,
                      session=Depends(db.get_session),
                      user=Security(permission.security, scopes=['role:write'])):
    return RoleUserView.delete_role_users(session, id, body.ids)
